package com.sk.aop.proxy;

import org.springframework.cglib.proxy.Enhancer;

import java.lang.reflect.Proxy;

public class Main {
    public static void main(String[] args) {
        /**
         * 静态代理
         */
        HouseProxy houseProxy = new HouseProxy(new RealHouseSubject());
        houseProxy.rentHouse();
        HouseSubject houseSubject = new RealHouseSubject();
        houseSubject.rentHouse();
        System.out.println("=========================================");

        /**
         * JDK动态代理(只能代理接口)
         */
        RealHouseSubject target = new RealHouseSubject();
        //动态生成代理对象 代理接口,运行成功 (代理类会运行失败)
        HouseSubject proxy1 = (HouseSubject) Proxy.newProxyInstance(
                target.getClass().getClassLoader(),//代理对象使用的加载器
                new Class[]{HouseSubject.class},//我们要实现的是什么接口
                new JDKInvocationHandler(target));//代理工作的实现类
        proxy1.rentHouse();
        proxy1.sellHouse();
        System.out.println("=========================================");

        /**
         *  使用CGLib 完成代理
         */
        RealHouseSubject houseSubject1 = new RealHouseSubject();
        //代理接口运行成功
        HouseSubject o = (HouseSubject) Enhancer.create(houseSubject1.getClass()//创建代理对象的类型
                , new CGLibMethodInterceptor(houseSubject1));//功能的增强
        o.rentHouse();
        o.sellHouse();
        System.out.println("=========================================");
        //代理类 也运行成功了
        RealHouseSubject o2 = (RealHouseSubject) Enhancer.create(houseSubject1.getClass()//创建代理对象的类型
                , new CGLibMethodInterceptor(houseSubject1));
        o2.rentHouse();
        o2.sellHouse();


    }
}
